import { defineStore } from "pinia";
import { AuthState } from "@/stores/interface";
import { getAuthButtonListApi, getAuthMenuListApi } from "@/api/modules/login";
import { getFlatMenuList, getShowMenuList, getAllBreadcrumbList, getMenuList } from "@/utils";
import { getMenuByUserId, getDict } from "@/api/modules/sys";
import { useUserStore } from "@/stores/modules/user";
export const useAuthStore = defineStore({
  id: "geeker-auth",
  state: (): AuthState => ({
    // 按钮权限列表
    authButtonList: {},
    // 菜单权限列表
    authMenuList: [],
    // 当前页面的 router name，用来做按钮权限筛选
    routeName: ""
  }),
  getters: {
    // 按钮权限列表
    authButtonListGet: state => state.authButtonList,
    // 菜单权限列表 ==> 这里的菜单没有经过任何处理
    authMenuListGet: state => state.authMenuList,
    // 菜单权限列表 ==> 左侧菜单栏渲染，需要剔除 isHide == true
    showMenuListGet: state => getShowMenuList(state.authMenuList),
    // 菜单权限列表 ==> 扁平化之后的一维数组菜单，主要用来添加动态路由
    flatMenuListGet: state => getFlatMenuList(state.authMenuList),
    // 递归处理后的所有面包屑导航列表
    breadcrumbListGet: state => getAllBreadcrumbList(state.authMenuList)
  },
  actions: {
    // Get AuthButtonList
    async getAuthButtonList() {
      const { data } = await getAuthButtonListApi();
      this.authButtonList = data;
      console.log(this.authButtonList);
    },
    // Get AuthMenuList
    async getAuthMenuList() {
      const { data } = await getAuthMenuListApi();
      this.authMenuList = data;
    },
    // get AuthMenu
    async getAuthMenu() {
      const userStore = useUserStore();
      // 获取菜单字典
      const { data: menuDicList } = await getDict({ parentId: window.staticConfig.dictionary.menuId });
      // 获取权限
      const menuId = menuDicList.find(item => item.name === "菜单");
      const buttonId = menuDicList.find(item => item.name === "菜单按钮");
      const { data } = await getMenuByUserId({ userId: userStore.userInfo.id });

      // 菜单
      const menuList = data?.filter(item => item).filter(item => item.typeId === menuId.id);
      this.authMenuList = getMenuList(menuList);
      console.log(this.authMenuList);

      // 按钮
      let buttonList = data?.filter(item => item).filter(item => item.typeId === buttonId.id);
      if (buttonList && buttonList.length) {
        buttonList = buttonList.reduce((total, item) => {
          if (item.perms) {
            let arr = item.perms.split(":");
            if (item.componentName in total) {
              total[item.componentName].push(arr[arr.length - 1]);
            } else {
              total[item.componentName] = [arr[arr.length - 1]];
            }
          }
          return total;
        }, {});
      }
      this.authButtonList = buttonList || {};
      console.log(buttonList);
    },
    // Set RouteName
    async setRouteName(name: string) {
      this.routeName = name;
    }
  }
});
